/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormSeries.java
 *
 * Created on 24/01/2012, 08:03:03
 */
package Formularios;

import Atributos.Curso;
import Atributos.Serie;
import Metodos.CursoMet;
import Metodos.MinimizaTela;
import Metodos.SerieMet;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Andre
 */
public class FormSeries extends javax.swing.JFrame {
MinimizaTela tela= new MinimizaTela();  
 String escolha;    
 Curso curso=new Curso();
 CursoMet cursomet=new CursoMet();
 private List<Curso> listaC;
 Serie serie= new Serie();
 SerieMet seriemet=new SerieMet();
 DefaultTableModel tmSerie = new DefaultTableModel(null, new String[]{"Ano", "Curso", "Turma"});
 
 ListSelectionModel lsmSerie;
 private List<Serie> listaS;
    public FormSeries() {
        try {
            
                    tela.Minimiza(1);
        } catch (SQLException ex) {
            Logger.getLogger(FormCursos.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
      BufferedImage image=null;
        File imageFile=new File(".\\src\\Imagens\\logo3.png");
        try {
            image=ImageIO.read(imageFile);
            
        } catch (IOException ex) {
        }
        this.setIconImage(image);
        
//        BufferedImage image=new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
//        setIconImage(image);
        DesabilitaAdicionar();
        DesabilitaDeletar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jPanel1 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        jRB_adicionar = new javax.swing.JRadioButton();
        jRB_deletar = new javax.swing.JRadioButton();
        buton_adicionar = new javax.swing.JLabel();
        buton_deletar = new javax.swing.JLabel();
        jl_serie = new javax.swing.JLabel();
        jRB_1 = new javax.swing.JRadioButton();
        jRB_3 = new javax.swing.JRadioButton();
        jCB_curso = new javax.swing.JComboBox();
        jl_curso = new javax.swing.JLabel();
        jl_descricao = new javax.swing.JLabel();
        jCB_descricao = new javax.swing.JComboBox();
        jRB_2 = new javax.swing.JRadioButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTTabela_Serie = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Série");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setLayout(null);

        jSeparator1.setBackground(new java.awt.Color(255, 153, 0));
        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jPanel1.add(jSeparator1);
        jSeparator1.setBounds(170, 20, 11, 370);

        jRB_adicionar.setBackground(new java.awt.Color(0, 0, 0));
        buttonGroup1.add(jRB_adicionar);
        jRB_adicionar.setFont(new java.awt.Font("D3 Euronism italic", 0, 18)); // NOI18N
        jRB_adicionar.setForeground(new java.awt.Color(255, 102, 0));
        jRB_adicionar.setText("Adicionar");
        jRB_adicionar.setFocusPainted(false);
        jRB_adicionar.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRB_adicionarItemStateChanged(evt);
            }
        });
        jPanel1.add(jRB_adicionar);
        jRB_adicionar.setBounds(10, 80, 150, 30);

        jRB_deletar.setBackground(new java.awt.Color(0, 0, 0));
        buttonGroup1.add(jRB_deletar);
        jRB_deletar.setFont(new java.awt.Font("D3 Euronism italic", 0, 18)); // NOI18N
        jRB_deletar.setForeground(new java.awt.Color(255, 102, 0));
        jRB_deletar.setText("<html>Deletar<br><br>Visualizar");
        jRB_deletar.setFocusPainted(false);
        jRB_deletar.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRB_deletarItemStateChanged(evt);
            }
        });
        jPanel1.add(jRB_deletar);
        jRB_deletar.setBounds(10, 250, 150, 80);

        buton_adicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/butonadicionar.jpg"))); // NOI18N
        buton_adicionar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        buton_adicionar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buton_adicionarMouseClicked(evt);
            }
        });
        jPanel1.add(buton_adicionar);
        buton_adicionar.setBounds(440, 340, 190, 40);

        buton_deletar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/butondeletar.jpg"))); // NOI18N
        buton_deletar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        buton_deletar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buton_deletarMouseClicked(evt);
            }
        });
        jPanel1.add(buton_deletar);
        buton_deletar.setBounds(440, 340, 190, 40);

        jl_serie.setBackground(new java.awt.Color(0, 0, 0));
        jl_serie.setFont(new java.awt.Font("D3 Euronism italic", 1, 14)); // NOI18N
        jl_serie.setForeground(new java.awt.Color(255, 255, 255));
        jl_serie.setText("Serie:");
        jPanel1.add(jl_serie);
        jl_serie.setBounds(210, 80, 79, 17);

        jRB_1.setBackground(new java.awt.Color(0, 0, 0));
        buttonGroup2.add(jRB_1);
        jRB_1.setFont(new java.awt.Font("D3 Euronism italic", 0, 24)); // NOI18N
        jRB_1.setForeground(new java.awt.Color(255, 102, 0));
        jRB_1.setText("1");
        jRB_1.setFocusPainted(false);
        jPanel1.add(jRB_1);
        jRB_1.setBounds(230, 120, 50, 37);

        jRB_3.setBackground(new java.awt.Color(0, 0, 0));
        buttonGroup2.add(jRB_3);
        jRB_3.setFont(new java.awt.Font("D3 Euronism italic", 0, 24)); // NOI18N
        jRB_3.setForeground(new java.awt.Color(255, 102, 0));
        jRB_3.setText("3");
        jRB_3.setFocusPainted(false);
        jPanel1.add(jRB_3);
        jRB_3.setBounds(230, 240, 50, 37);

        jCB_curso.setBackground(new java.awt.Color(0, 0, 0));
        jCB_curso.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        jCB_curso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCB_cursoActionPerformed(evt);
            }
        });
        jPanel1.add(jCB_curso);
        jCB_curso.setBounds(430, 170, 190, 27);

        jl_curso.setBackground(new java.awt.Color(0, 0, 0));
        jl_curso.setFont(new java.awt.Font("D3 Euronism italic", 1, 14)); // NOI18N
        jl_curso.setForeground(new java.awt.Color(255, 255, 255));
        jl_curso.setText("Curso:");
        jPanel1.add(jl_curso);
        jl_curso.setBounds(330, 170, 79, 17);

        jl_descricao.setBackground(new java.awt.Color(0, 0, 0));
        jl_descricao.setFont(new java.awt.Font("D3 Euronism italic", 1, 14)); // NOI18N
        jl_descricao.setForeground(new java.awt.Color(255, 255, 255));
        jl_descricao.setText("Turma:");
        jPanel1.add(jl_descricao);
        jl_descricao.setBounds(670, 170, 118, 17);

        jCB_descricao.setBackground(new java.awt.Color(0, 0, 0));
        jCB_descricao.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        jPanel1.add(jCB_descricao);
        jCB_descricao.setBounds(790, 170, 60, 27);

        jRB_2.setBackground(new java.awt.Color(0, 0, 0));
        buttonGroup2.add(jRB_2);
        jRB_2.setFont(new java.awt.Font("D3 Euronism italic", 0, 24)); // NOI18N
        jRB_2.setForeground(new java.awt.Color(255, 102, 0));
        jRB_2.setText("2");
        jRB_2.setFocusPainted(false);
        jPanel1.add(jRB_2);
        jRB_2.setBounds(230, 180, 50, 37);

        jScrollPane1.setBackground(new java.awt.Color(0, 0, 0));
        jScrollPane1.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 0, 0)));
        jScrollPane1.setForeground(new java.awt.Color(51, 204, 0));
        jScrollPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jTTabela_Serie.setBackground(new java.awt.Color(0, 0, 0));
        jTTabela_Serie.setForeground(new java.awt.Color(255, 255, 255));
        jTTabela_Serie.setModel(tmSerie);
        jTTabela_Serie.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jTTabela_Serie.setGridColor(new java.awt.Color(255, 255, 255));
        jTTabela_Serie.setInheritsPopupMenu(true);
        jTTabela_Serie.setSelectionBackground(new java.awt.Color(255, 255, 255));
        jTTabela_Serie.setSelectionForeground(new java.awt.Color(0, 0, 0));
        jTTabela_Serie.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmSerie = jTTabela_Serie.getSelectionModel();
        lsmSerie.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
                if(! e.getValueIsAdjusting()){
                    JTTabelaLinhaSelecionada(jTTabela_Serie);
                }
            }
        }
    );
    jScrollPane1.setViewportView(jTTabela_Serie);

    jPanel1.add(jScrollPane1);
    jScrollPane1.setBounds(200, 70, 670, 220);

    jPanel1.setBounds(0, 0, 1010, 900);
    jDesktopPane1.add(jPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 905, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
    );

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-921)/2, (screenSize.height-449)/2, 921, 449);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    try {
            tela.Minimiza(0);
        } catch (SQLException ex) {
            Logger.getLogger(FormCursos.class.getName()).log(Level.SEVERE, null, ex);
        }
       java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ChamaLayout().setVisible(true);
            }
        }); 
    }//GEN-LAST:event_formWindowClosed

    private void jRB_adicionarItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRB_adicionarItemStateChanged
       DesabilitaDeletar();
       escolha=jRB_adicionar.getText();
       ChamaEscolha(escolha);
       InicializaDadosADD();
    }//GEN-LAST:event_jRB_adicionarItemStateChanged

    private void jRB_deletarItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRB_deletarItemStateChanged
 if(jRB_deletar.isSelected()){
        if(VerificaseVazio()){
        DesabilitaAdicionar();
        escolha=jRB_deletar.getText();
       ChamaEscolha(escolha);    
        try {
            listaS= seriemet.Buscar("%");
        } catch (SQLException ex) {
            Logger.getLogger(FormSeries.class.getName()).log(Level.SEVERE, null, ex);
        }
         mostraPesquisa(listaS);
         }else{
          JOptionPane.showMessageDialog(null, "Não há series a serem deletadas!");
          DesabilitaAdicionar();
          buttonGroup1.clearSelection();
      }
}
    }//GEN-LAST:event_jRB_deletarItemStateChanged

    private void jCB_cursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCB_cursoActionPerformed
AtualizaDadosAdicionar();       
    }//GEN-LAST:event_jCB_cursoActionPerformed

    private void buton_adicionarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buton_adicionarMouseClicked
     if(VerificaDadosCorretos()){
         String a=null;
         curso.setNome(jCB_curso.getSelectedItem().toString());
         curso.setDescrição(jCB_descricao.getSelectedItem().toString());
         if(jRB_1.isSelected()){
            a=jRB_1.getText(); 
         }
         if(jRB_2.isSelected()){
            a=jRB_2.getText(); 
         }
         if(jRB_3.isSelected()){
            a=jRB_3.getText(); 
         }
         serie.setNome(a);
         serie.setId_curso(cursomet.Buscar_ID_Curso(jCB_curso.getSelectedItem().toString()));
         serie.setId_turma(cursomet.Buscar_ID_Descricao(curso.getId_curso(), jCB_descricao.getSelectedItem().toString(),0));
         if(seriemet.VerificaBD(curso,serie)){
                try {
                    seriemet.AdicionaSerie(serie);
                } catch (SQLException ex) {
                    Logger.getLogger(FormSeries.class.getName()).log(Level.SEVERE, null, ex);
                }
                JOptionPane.showMessageDialog(null, "Adicionado com sucesso!");
         }else{
             JOptionPane.showMessageDialog(null, "Esta serie ja existe!");
         }
     }else{
         JOptionPane.showMessageDialog(null, "Dados Incorretos");
     }
    }//GEN-LAST:event_buton_adicionarMouseClicked

    private void buton_deletarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buton_deletarMouseClicked
if(jTTabela_Serie.getSelectedRow()!=-1){     
        int resp = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir esta serie?",
                "Confirmação", JOptionPane.YES_NO_OPTION);

        if (resp == JOptionPane.YES_NO_OPTION) {
            try {
                curso.setNome(listaS.get(jTTabela_Serie.getSelectedRow()).getNome());
               
                curso.setDescrição(listaS.get(jTTabela_Serie.getSelectedRow()).getTurma());
                seriemet.Excluir(listaS.get(jTTabela_Serie.getSelectedRow()).getId(),curso);
            } catch (SQLException ex) {
                Logger.getLogger(FormSeries.class.getName()).log(Level.SEVERE, null, ex);
            }
            JOptionPane.showMessageDialog(null, "Excluído com sucesso!");
            try {
            listaS= seriemet.Buscar("%");
        } catch (SQLException ex) {
            Logger.getLogger(FormSeries.class.getName()).log(Level.SEVERE, null, ex);
        }
         mostraPesquisa(listaS);
        }
}else{
    JOptionPane.showMessageDialog(null, "Nada selecionado");
}
    }//GEN-LAST:event_buton_deletarMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormSeries.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormSeries.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormSeries.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormSeries.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FormSeries().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel buton_adicionar;
    private javax.swing.JLabel buton_deletar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JComboBox jCB_curso;
    private javax.swing.JComboBox jCB_descricao;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRB_1;
    private javax.swing.JRadioButton jRB_2;
    private javax.swing.JRadioButton jRB_3;
    private javax.swing.JRadioButton jRB_adicionar;
    private javax.swing.JRadioButton jRB_deletar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTTabela_Serie;
    private javax.swing.JLabel jl_curso;
    private javax.swing.JLabel jl_descricao;
    private javax.swing.JLabel jl_serie;
    // End of variables declaration//GEN-END:variables

    private void DesabilitaAdicionar() {
        buttonGroup2.clearSelection();
        jl_curso.setVisible(false);
        jl_descricao.setVisible(false);
        jl_serie.setVisible(false);
        jRB_1.setVisible(false);
        jRB_2.setVisible(false);
        jRB_3.setVisible(false);
        jCB_curso.setVisible(false);
        jCB_descricao.setVisible(false);
        buton_adicionar.setVisible(false);
    }

    private void DesabilitaDeletar() {
        buton_deletar.setVisible(false);
        jTTabela_Serie.clearSelection();
         while (tmSerie.getRowCount() > 0) {
            tmSerie.removeRow(0);
        }
         jTTabela_Serie.setVisible(false);
         jScrollPane1.setVisible(false);
    }

    private void ChamaEscolha(String escolha) {
         if("Adicionar".equals(escolha)){
        jl_curso.setVisible(true);
        jl_descricao.setVisible(true);
        jl_serie.setVisible(true);
        buton_adicionar.setVisible(true);
        jRB_1.setVisible(true);
        jRB_2.setVisible(true);
        jRB_3.setVisible(true);
        jCB_curso.setVisible(true);
        jCB_descricao.setVisible(true);
        }else if("<html>Deletar<br><br>Visualizar".equals(escolha)){
         buton_deletar.setVisible(true); 
         jTTabela_Serie.setVisible(true);
         jScrollPane1.setVisible(true);
        }
    }

    private void InicializaDadosADD() {
        if(VerificaseHaCuros()){
        String[] cursos = cursomet.Buscar_Nome_Cursos();
        jCB_curso.setModel(new javax.swing.DefaultComboBoxModel(cursos));
        String nome= jCB_curso.getSelectedItem().toString();
        listaC=cursomet.Buscar_Descricaolist(nome);
        String[] descrição = new String[listaC.size()];
        for(int i = 0;listaC.size()>i;i++){
        curso = listaC.get(i);
        descrição[i] = curso.getDescrição(); 
        }
        jCB_descricao.setModel(new javax.swing.DefaultComboBoxModel(descrição));
        }
    }

    private void AtualizaDadosAdicionar() {
        String nome= jCB_curso.getSelectedItem().toString();
        listaC=cursomet.Buscar_Descricaolist(nome);
        String[] descrição = new String[listaC.size()];
        for(int i = 0;listaC.size()>i;i++){
        curso = listaC.get(i);
        descrição[i] = curso.getDescrição(); 
        }
        jCB_descricao.setModel(new javax.swing.DefaultComboBoxModel(descrição));
    }

    private boolean VerificaDadosCorretos() {
         if( buttonGroup2.getSelection()==null || jCB_curso.getSelectedItem()==null) {
            return false;
        }else {
            return true;
        }
    }
    
    private void JTTabelaLinhaSelecionada(JTable tabela) {
        
  }

    private void mostraPesquisa(List<Serie> listaS) {
         while (tmSerie.getRowCount() > 0) {
            tmSerie.removeRow(0);
        }
        if ( listaS.isEmpty()) {
        } else {
            String[] linha = new String[]{null, null, null };
            for (int i = 0; i <  listaS.size(); i++) {
                tmSerie.addRow(linha);
                tmSerie.setValueAt(listaS.get(i).getNome(), i, 0);
                tmSerie.setValueAt(listaS.get(i).getCurso(), i, 1);
                tmSerie.setValueAt(listaS.get(i).getTurma(), i, 2);
                
            }
        }
    }

    private boolean VerificaseVazio() {
       try {
            listaS= seriemet.Buscar("%");
        } catch (SQLException ex) {
            Logger.getLogger(FormSeries.class.getName()).log(Level.SEVERE, null, ex);
        }
       if(listaS.isEmpty()){
          return false; 
       }else{
           return true;
       }
    }

    private boolean VerificaseHaCuros() {
        if(cursomet.Buscar_Se_Ha_Curso()){
        String[] nomes=cursomet.Buscar_Nome_Cursos();
        if(nomes.length==0){
          return false;  
        }else{
            return true;
        }
     }else{
            return false;
        }
    }    
    
    
}
